/**
 *
 */
package com.cms.admin.action.common;


import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.cms.admin.action.BaseAction;
import com.cms.admin.model.DepartmentList;

import com.cms.admin.model.FuncList;
import com.cms.admin.model.UserList;

import com.cms.admin.service.common.FuncListService;
import com.cms.admin.service.employee.DepartmentListService;
import com.cms.admin.service.privilege.UserListService;
import com.cms.admin.util.Constants;
import com.cms.admin.util.MD5Password;
import com.opensymphony.xwork2.ActionContext;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;

/**
 * @author bobo
 */
public class LoginAction extends BaseAction {
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private Map<String, Object> session;
    private Map<String, Object> application;
    private String username;

    private String password;

    private UserListService userListService;

    private UserList user;

    private String loginIp;

    private String loginMac;

    private String loginMachineName;


    private String res;

    private DepartmentListService departmentService;

    private List<DepartmentList> departmentList;

    //菜单树
    List<FuncList> tree = null;

    /**
     * @return the tree
     */
    public List<FuncList> getTree() {
        return tree;
    }


    /**
     * @param tree the tree to set
     */
    public void setTree(List<FuncList> tree) {
        this.tree = tree;
    }

    private FuncListService funcListService;

    /**
     * @return the departmentService
     */
    public DepartmentListService getDepartmentService() {
        return departmentService;
    }


    /**
     * @param departmentService the departmentService to set
     */
    public void setDepartmentService(DepartmentListService departmentService) {
        this.departmentService = departmentService;
    }


    /**
     * 处理菜单展示
     *
     * @return
     */
    public void getMenus() {


        tree = funcListService.getAllMenu();

        //此处做页面权限的控制，如果页面id未在角色列表中，则不展示此页面
        //特别重要：不能直接对tree在遍历的过程中将list中的对象remove掉，否则会抛出异常java.util.ConcurrentModificationException
        Iterator keys = tree.iterator();
        FuncList key = null;
        while (keys.hasNext()) {
            key = (FuncList) keys.next();

		        /*
		        Short menuId=key.getMenuId();

	        	//System.out.println("查询到menuId:"+menuId+"|"+key.getLabel());
				
		        if(null!=role && null!=role.getPages())
				{
					
		        	//System.out.println("查询到menuId:"+menuId+"|"+role.getPages().equals(String.valueOf(menuId)));
					
					//和用户的页面不相等或是未找到用户的权限
					//用户角页面列表中如果不存在此页面，则需要将此页面去除
					if(role.getPages().indexOf(String.valueOf(menuId))<0 )
					{
						keys.remove();
					}
					
				}
		        
		          */

        }


//			//获取到 所有菜单
//		   List<Menu>  allMenuList = menuService.getAllMenu();
//		   
//			for( Menu menu:allMenuList)
//			{
//				//当前菜单 不为空
//				if(null!=menu)
//				{
//					
//					Short menuId=menu.getMenuId();
//					
//					//System.out.println("查询到menuId:"+menuId+"--label"+menu.getLabel());
//					//用户没有此顶级菜单，则不需要再查询此父菜单下的子菜单
//					if(null!=role && null!=role.getPages())
//					{
//						
//						//System.out.println("查询到menuId:"+menuId+"|"+role.getPages().equals(String.valueOf(menuId)));
//						
//						//和用户的页面不相等或是未找到用户的权限
//						if(role.getPages().indexOf(String.valueOf(menuId))<0 )
//						{
//							continue;
//						}
//						
//					}
//					
//					//获取当前菜单的父亲菜单id
//					Short parentMenuId=menu.getParentId();
//					
//					//顶级菜单为0 才展示，否则不展示，预防假设直接选择到最下面一级菜单，但顶级菜单没有选择，
//					//这个问题其实是应该在菜单选择时就处理好，不应该放到代码中，因为那样属于无效数据
//					//为0就是顶级菜单
//					if(0==parentMenuId)
//					{
//						//System.out.println("查询到顶级菜单menuId:"+menuId+"--label"+menu.getLabel()+"--getParentId:"+parentMenuId);
//						
//						//找到顶级菜单下面所有的菜单
//						 List<Menu>   	subMenuList=null;
//
//						 
//							
//						 subMenuList = menuService.getSubMenu(menuId);
//						
//					    //子菜单不为空则放入与顶级菜单对应的关系中
//						if(null!=subMenuList && subMenuList.size()>0)
//						{
//							//System.out.println("  ");
//						 
//							
//							for( Menu m:subMenuList)
//							{
//								 //System.out.print (m.getMenuId()+"---"+m.getLabel());
//							}
//							
//							menuMap.put(menu, subMenuList);	
//						}
//						else 
//						{ 
//							//System.out.println("我到这了");
//							menuMap.put(menu, null);
//						}
//					}
//					
//				}
//				
//			}
//			//System.out.println();
//			//System.out.println("=========================");
//
//		 


//			
//		Set 	 s= menuMap.keySet() ;
//		for(Menu dataKey : menuMap.keySet()) 
//		{ 
//			//System.out.println(dataKey.getMenuId()+"--"+dataKey.getLabel() ); 
//			
//			for(Menu l : menuMap.get(dataKey)) 
//			{ 
//				//System.out.println(l.getMenuId()+"-----------"+l.getLabel() ); 
//				
//			
//			}
//		}


    }

    /**
     * 构造方法
     */
    public LoginAction() {

        session = ActionContext.getContext().getSession();
        application = ActionContext.getContext().getApplication();
    }


    @Override
    public String execute() throws Exception {

        HttpServletRequest request = ServletActionContext.getRequest();

        username = request.getParameter("userid");
        password = request.getParameter("password");
        boolean checkMac = false;

        LOG.info(" loginIp:" + loginIp);
        LOG.info(" loginMac:" + loginMac);
        LOG.info(" loginMachineName:" + loginMachineName);
        LOG.info(" username:" + username);
        LOG.info(" password:" + password);


        //判断是否校验MAC
        //GlobalConfig globalConfig = globalConfigService.selectByConfigKey(Constants.CONSTANTS_CHECK_MAC);


        LOG.info(" checkMac:" + checkMac);
        //不校验mac的验证
        if (checkMac == false) {
            if (checkLoginUser()) {
                getMenus();

                //LOG.info(" sysLoginLogService:" + sysLoginLogService);
                //sysLoginLogService.insert(logRecord);
                return SUCCESS;
            } else {
                return INPUT;
            }

        }
        //校验mac的验证
        else {

            if (null == loginMac || "".equals(loginMac)) {
                res = "您无权限登录，请联系系统管理员！";
                LOG.info(" mac invalid:" + loginMac);
                return INPUT;
            }


            if (checkLoginUser()) {
                //sysLoginLogService.insert(logRecord);
                return SUCCESS;
            } else {

                res = "您无权限登录，请联系系统管理员！";

                return INPUT;
            }


        }


    }

    public boolean checkLoginUser() {

        UserList user = new UserList();
        // 登录时用户名和密码都不能为空
        if (null != username && !"".equals(username) && null != password && !"".equals(password)) {

            String aaa=MD5Password.getEncodedPassword(password);
            LOG.info(" 输入密码password:" + aaa);

            // 调用服务层
            user = userListService.getByName(username);

            if (null != user) {
                String passwordFromDB = user.getPassword();

                boolean yesOrNo = false;

                yesOrNo = MD5Password.testPassword_Hex(password, passwordFromDB);

                // 如果用户名正确，密码也正确，则登录成功

                if (yesOrNo)

                {
                    LOG.info("<<--user " + user.getUserName() + " is login-->>");


                    // 登录成功前将最此次登录的时候和IP记录下来

                    // 此处处理

				 
					 
						
				 
				 /*

					 //如果角色是root则重新加载一次部门数据
					 if("root".equals(user.getRole().getRoleName())||"管理员".equals(user.getRole().getRoleName()))
					 {
						 departmentList =  departmentService.getAllRows();
						 
						 StringBuffer dsb= new StringBuffer();
						 
						 for(Department dep:departmentList)
						 {
							 dsb.append(dep.getDeptNo());
							 dsb.append(",");
						 }
						 LOG.info("root role department:"+dsb.toString());
						 user.getRole().setResources(dsb.toString());
					 }
				 */

                    // 此处设置为已经登录

                    session.put(Constants.LOGIN_STATE, "true");

                    session.put(Constants.USER_OBJECT, user);

                    //session.put(Constants.ROLE_OBJECT, user.getRole());

                    super.setSession(session);


                    return true;
                } else {

                    LOG.info("密码不正确!");
                    res = "密码不正确!";
                    return false;

                }

            }

            LOG.info("无此用户:" + username);
            res = "无此用户:" + username;
            return true;

        } else {

            LOG.info("登录时未输入用户名或密码!");
            res = "登录时未输入用户名或密码!";
            return true;
        }

    }

    /**
     * 登出撤消session
     *
     * @param
     */
    @SuppressWarnings("unchecked")
    public String logout() {

        UserList userSeesion = (UserList) this.att.get(Constants.USER_OBJECT);
        String userName = userSeesion.getUserName();


        session.remove(Constants.LOGIN_STATE);
        session.remove(Constants.USER_OBJECT);
        session.remove(Constants.ROLE_OBJECT);


        //sysLoginLogService.insert(logRecord);
        LOG.info("<<--user " + userName + " is logout-->>");
        return SUCCESS;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


    public UserListService getUserListService() {
        return userListService;
    }


    public void setUserListService(UserListService userListService) {
        this.userListService = userListService;
    }


    /**
     * @return the loginIp
     */
    public String getLoginIp() {
        return loginIp;
    }


    /**
     * @param loginIp the loginIp to set
     */
    public void setLoginIp(String loginIp) {
        this.loginIp = loginIp;
    }


    /**
     * @return the loginMac
     */
    public String getLoginMac() {
        return loginMac;
    }


    /**
     * @param loginMac the loginMac to set
     */
    public void setLoginMac(String loginMac) {
        this.loginMac = loginMac;
    }


    /**
     * @return the loginMachineName
     */
    public String getLoginMachineName() {
        return loginMachineName;
    }


    /**
     * @param loginMachineName the loginMachineName to set
     */
    public void setLoginMachineName(String loginMachineName) {
        this.loginMachineName = loginMachineName;
    }


    /**
     * @return the res
     */
    public String getRes() {
        return res;
    }


    /**
     * @param res the res to set
     */
    public void setRes(String res) {
        this.res = res;
    }


    public FuncListService getFuncListService() {
        return funcListService;
    }


    public void setFuncListService(FuncListService funcListService) {
        this.funcListService = funcListService;
    }


}
